package com.house.generator;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.house.framework.controller.BaseController;
import com.house.framework.entity.BaseEntity;
import com.house.framework.mapper.MapperBase;
import com.house.framework.service.impl.ServiceBaseImpl;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class MyCodeGenerator {

    public static final String PARENT_PACKAGE = "com.house.business";

    public static final String ENTITY_PACKAGE = "entity";

    public static final Boolean GET_ALL_TABLE = true;
    public static String dir = System.getProperty("user.dir");

    /**
     * 需要生成的表
     *
     * @return
     */
    public static List<String> getTables() {
        if (GET_ALL_TABLE) {
            return ConnectionUtils.getAllTable();
        }
        return ConnectionUtils.getTableListWithPrefix(new String[]{"T_Dict"});
    }

    public static void main(String[] args) {
        try {

            String path = null;
            while (path == null || path.length() == 0) {
                Scanner scanner = new Scanner(System.in);
                System.out.println("请输入保存的路径：");
                path = scanner.nextLine().trim();
            }
            dir = path;

            String auth = null;
            while (auth == null || auth.length() == 0) {
                Scanner scanner = new Scanner(System.in);
                System.out.println("请输入作者：");
                auth = scanner.nextLine().trim();
            }


            String tables = null;
            while (tables == null || tables.length() == 0) {
                Scanner scanner = new Scanner(System.in);
                System.out.println("请输入表名以逗号分割（*为所有表）：");
                tables = scanner.nextLine().trim();
            }


            String over = null;
            while (over == null || (!over.equals("Y") && !over.equals("N"))) {
                Scanner scanner = new Scanner(System.in);
                System.out.println("是否覆盖之前代码(Y/N)：");
                over = scanner.nextLine().trim().toUpperCase();
            }

            List<String> tableList;
            if (tables.equals("*")) {
                tableList = ConnectionUtils.getAllTable();
            } else {
                tableList = Arrays.stream(tables.split(",")).collect(Collectors.toList());
            }


            String finalAuth = auth;
            boolean override = over.equals("Y");
            FastAutoGenerator.create(ConnectionUtils.url, ConnectionUtils.userName, ConnectionUtils.password)
                    .globalConfig(builder -> {
                        builder.author(finalAuth)               //作者
                                .outputDir(dir + "\\WebServiceApi\\src\\main\\java")    //输出路径(写到java目录)
                                .enableSwagger()           //开启swagger
                                .commentDate("yyyy-MM-dd");
                        if (override) {
                            builder.fileOverride(); //开启覆盖之前生成的文件
                        }

                    })
                    .packageConfig(builder -> {
                        builder.parent(PARENT_PACKAGE)
                                //.moduleName("api")
                                .entity("entity")
                                .service("service")
                                .serviceImpl("service.impl")
                                .controller("controller")
                                .mapper("mapper")
                                .xml("mapper")
                                .pathInfo(Collections.singletonMap(OutputFile.mapperXml, dir + "\\WebServiceApi\\src\\main\\resources\\mapper\\business"));
                    })
                    .strategyConfig(builder -> {
                        //builder.addInclude(tables)
                        builder.addInclude(tableList)//.addExclude("TB_MODULE","TB_PARAM","TB_SYSTEM","TB_WEBAPI","V_Sys_AuthorizeUser","V_Sys_DepartmentUser","V_Sys_RoleUser","V_Sys_UserList")
                                .addTablePrefix("T_")
                                .addFieldPrefix("F_")
                                .entityBuilder()
                                .superClass(BaseEntity.class)
                                .enableLombok()
                                .logicDeleteColumnName("F_IsDeleted")
                                .enableTableFieldAnnotation()
                                .serviceBuilder()
                                .formatServiceFileName("%sService")
                                .superServiceImplClass(ServiceBaseImpl.class)
                                .formatServiceImplFileName("%sServiceImpl")
                                .controllerBuilder()
                                .enableHyphenStyle()
                                .superClass(BaseController.class)
                                .formatFileName("%sController")
                                .enableRestStyle()
                                .mapperBuilder()
                                .superClass(MapperBase.class)
                                .formatMapperFileName("%sMapper")
                                .enableMapperAnnotation()
                                .formatXmlFileName("%sMapper").enableBaseResultMap().enableBaseColumnList();
                    })
                    .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                    .injectionConfig(builder -> {
                        builder.customMap(new HashMap<String, Object>() {{
                            put("util", new CodeUtils());//代码处理工具类
                        }});
                    })
                    .execute();
            generateVO();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private static void generateVO() {
        String outputDir = dir + "\\WebServiceApi\\src\\main\\java";
        String voPackage = outputDir + "\\" + PARENT_PACKAGE.replaceAll("\\.", "\\\\") + "\\" + "vo";
        String entityPackage = outputDir + "\\" + PARENT_PACKAGE.replaceAll("\\.", "\\\\") + "\\" + "entity";
        File voPackageFile = new File(voPackage);
        if (!voPackageFile.exists()) {
            voPackageFile.mkdirs();
        }
        File entityPackageFile = new File(entityPackage);
        File[] entity = entityPackageFile.listFiles();
        for (File file : entity) {
            try {
                copyEntityFile(file, voPackage);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void copyEntityFile(File file, String voPackage) throws Exception {
        if (file.isDirectory()) {
            File[] entity = file.listFiles();
            for (File f : entity) {
                copyEntityFile(f, voPackage);
            }
        } else {
            String entityName = file.getName();
            String voName = entityName.replaceAll("\\.", "Vo.");
            File entityVoFile = new File(voPackage + "\\" + voName);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            if (entityVoFile.exists()) {
                entityVoFile.delete();
                entityVoFile.createNewFile();
            }
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                line = line.replaceAll("entity;", "vo;");
                line = line.replaceAll(entityName.substring(0, entityName.indexOf(".")), voName.substring(0, voName.indexOf(".")));
                if (line.trim().startsWith("}")) {
                    writeVoFile(entityVoFile, "    @ApiModelProperty(\"分页页码\")\n" +
                            "    @TableField(exist = false)\n" +
                            "    private Integer pageIndex;\n" +
                            "\n" +
                            "    @ApiModelProperty(\"每页记录条数\")\n" +
                            "    @TableField(exist = false)\n" +
                            "    private Integer pageSize;");
                }
                writeVoFile(entityVoFile, line);
            }
        }
    }

    public static void writeVoFile(File file, String text) throws Exception {
        FileWriter fw = new FileWriter(file, true);
        PrintWriter pw = new PrintWriter(fw);
        pw.println(text);
        pw.flush();
        fw.flush();
        pw.close();
        fw.close();
    }

    // 处理 all 情况
    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }
}
